﻿using Core.Com;
using Reader.SFC.Models;
using System;
using System.Linq;

namespace Reader.SFC
{
    public static class DataConvert
    {
        internal static string ConvertToString(this byte[] bytes, int startIndex, int length)
        {
            string str = string.Empty;
            for (int index = startIndex; index < length && index < bytes.Length; ++index)
                str += bytes[index].ToString("X2");
            return str;
        }
        internal static string ToASCII(this string str)
        {
            byte[] array = System.Text.Encoding.ASCII.GetBytes(str);
            string ret = "";
            for (int i = 0; i < array.Length; i++)
            {
                ret += (int)array[i];
            }
            return ret;
        }

        internal static string FromASCII(this string ascii)
        {   //数组array为对应的ASCII数组    
            string ret = "";
            for (int i = 0; i < ascii.Length / 2; i++)
            {
                int b = Convert.ToInt32(ascii.Substring(2 * i, 2));
                ret += Convert.ToChar(b);
            }
            return ret;
        }
        public static string FromASCII(this string ascii, params QR_Type[] qR_Types)
        {   //数组array为对应的ASCII数组  
            if (qR_Types == null)
            {
                return FromASCII(ascii);
            }
            else
            {
                var qr_type = qR_Types.OrderBy(p => p.Key).FirstOrDefault(p => p.Prefix.IsNotNull() && ascii.StartsWith(p.Prefix));
                if (qr_type != null)
                {
                    ascii = ascii.Replace(qr_type.Prefix, "");
                }
                var key = ascii.Length / 2;
                if (!qR_Types.Where(p => p.Key == key).Any()) return null;
                string ret = "";
                for (int i = 0; i < ascii.Length / 2; i++)
                {
                    int b = Convert.ToInt32(ascii.Substring(2 * i, 2));
                    ret += Convert.ToChar(b);
                }

                return ret;
            }
        }
    }
}
